class Subject { //被观察者
    constructor(name) {
        this.state = "";
        this.observers = [];
    }

    attach(ob) {//收集观察者
        this.observers.push(ob);
    }

    setState(newState) {// 被观察者状态发生改变，通知各个观察者
        this.setState = newState;
        this.observers.forEach(el => {
            el.update(this); // 通知各个观察者改变自身状态
        });
    }
}

class Observer {
    constructor(name) {
        this.name = name;
    }

    update(subject) {
        console.log("我观察的状态发生改变--" + subject.setState);
    }
}

// 以老师学生为例：老师观察学生
let student = new Subject("学生1");
let teacher1 = new Observer("语文老师");
let teacher2 = new Observer("数学老师");


student.attach(teacher1);
student.attach(teacher2);

student.setState("上课了")